package com.eshop.controller;


import com.eshop.config.VerificationCode;
import com.eshop.pojo.LoginParam;
import com.eshop.pojo.RespBean;
import com.eshop.pojo.User;
import com.eshop.service.LoginService;
import com.eshop.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.Principal;

@Api(tags = "登录相关")
@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private UserService userService;

    @ApiOperation(value = "生成验证码")
    @GetMapping("/verifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse resp) throws IOException {
        VerificationCode code = new VerificationCode();
        //生成验证码图片
        BufferedImage image = code.getImage();
        String text = code.getText();
        HttpSession session = request.getSession(true);
        session.setAttribute("verify_code", text);
        VerificationCode.output(image,resp.getOutputStream());
    }

    @ApiOperation(value = "获取当前用户信息")
    @GetMapping("/user/info")
    public User getUserInfo(Principal principal){
        if (null==principal){
            return null;
        }
        String username = principal.getName();
        User user = userService.queryUserByName(username);
        user.setPassword(null);//避免密码被泄露
        user.setRoles(userService.getRoles(user.getId()));
        return user;
    }


    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody LoginParam loginParam, HttpServletRequest request){
        return loginService.login(loginParam.getUsername(),loginParam.getPassword(),loginParam.getCode(),request);
    }


    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout(){
        return RespBean.success("注销成功！");
    }


}

